package cn.com.zpark.servlet_context;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.servlet_context
 * @ClassName: ServletContextDemo06
 * @Description:
 * @author: RZS
 * @date: 2021/11/13  14:39
 */
@WebServlet("/scd6.html")
public class ServletContextDemo06 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取web应用下的配置文件资源

        // 获取context对象
        ServletContext context = getServletContext();

        // 获取资源
        URL url = context.getResource("/WEB-INF/classes/db.properties");
        String path = context.getRealPath("/WEB-INF/classes/db.properties");
        InputStream stream = context.getResourceAsStream("/WEB-INF/classes/db.properties");
        System.out.println(url);
        System.out.println(path);
        System.out.println(stream);

        // 创建properties集合工具类
        Properties p = new Properties();
//        p.load(stream);
        // 解决配置文件中文乱码的问题
        p.load(new InputStreamReader(stream, "utf-8"));

        // 工具key获取value
        System.out.println(p.getProperty("name"));
        System.out.println(p.getProperty("url"));
        System.out.println(p.getProperty("desc"));


    }
}
